//
//  DTCLocalPushManager.m
//  LocalPush
//
//  Created by JianWei Chen on 2017/5/15.
//  Copyright © 2017年 JianWei Chen. All rights reserved.
//

#import "DTCLocalPushManager.h"
#import <AudioToolbox/AudioToolbox.h>

@interface DTCLocalPushManager ()<UNUserNotificationCenterDelegate>

@end

@implementation DTCLocalPushManager
#pragma mark - 初始化
+ (DTCLocalPushManager *)defalutService
{
    static DTCLocalPushManager *static_manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        static_manager = [[DTCLocalPushManager alloc]init];
    });
    return static_manager;
}

- (void)startLaunchOptions:(NSDictionary *)launchOptions
{
    [self registerAPNS];
}

- (void)addLocalNotificationByBody:(NSString *)body sound:(NSString *)soundName date:(NSDate *)date userInfo:(NSDictionary *)userInfo repeat:(BOOL)repeat
{
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        long long int value = [date timeIntervalSince1970] - [[NSDate date]timeIntervalSince1970];
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        UNNotificationSound *sound = [UNNotificationSound soundNamed:soundName];
        content.body = body;
        content.sound = sound;
        content.userInfo = userInfo;
        UNTimeIntervalNotificationTrigger *trigger1 = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:value repeats:repeat];
        NSString *requertIdentifier = [NSString stringWithFormat:@"DTCLocalNotificationIdentifier:%lld",(long long int)[date timeIntervalSince1970]];
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requertIdentifier content:content trigger:trigger1];
        
        //第五步：将通知加到通知中心
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            if (error) {
                NSLog(@"Error:%@",error);
            }else{
                NSLog(@"添加成功：local notification body:%@ time:%@",body,date);
            }
        }];
    }else{
        UILocalNotification *localnotification = [[UILocalNotification alloc]init];
        localnotification.fireDate = date;//通知触发时间
        localnotification.alertBody = body;//通知具体内容
        localnotification.repeatInterval = kCFCalendarUnitDay;
        localnotification.soundName = soundName;//通知时的音效
        [localnotification setUserInfo:userInfo];
        [[UIApplication sharedApplication] scheduleLocalNotification:localnotification];//立即发出本通知
    }
}

- (void)removeLocalNotification:(DTCLocalNotificationBlock)notificationRemoveAction
{
    float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (sysVer >= 10) {
        [[UNUserNotificationCenter currentNotificationCenter]getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
            NSMutableArray *removeList = [[NSMutableArray alloc]init];
            for (UNNotificationRequest *request in requests) {
                if (notificationRemoveAction(request)) {
                    [removeList addObject:request.identifier];
                    NSLog(@"移除了本地通知 %@",request.content.userInfo);
                }else{
                    NSLog(@"有本地通知未移除 %@",request.content.userInfo);
                }
            }
            [[UNUserNotificationCenter currentNotificationCenter]removePendingNotificationRequestsWithIdentifiers:removeList];
        }];
        
        [[UNUserNotificationCenter currentNotificationCenter]getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
            NSMutableArray *removeList = [[NSMutableArray alloc]init];
            for (UNNotification *request in notifications) {
                if (notificationRemoveAction(request)) {
                    [removeList addObject:request.request.identifier];
                    NSLog(@"移除了本地通知 %@",request.request.content.userInfo);
                }else{
                    NSLog(@"有本地通知未移除 %@",request.request.content.userInfo);
                }
            }
            [[UNUserNotificationCenter currentNotificationCenter]removePendingNotificationRequestsWithIdentifiers:removeList];
        }];
    }else{
        NSArray *narry=[[UIApplication sharedApplication] scheduledLocalNotifications];
        NSUInteger acount=[narry count];
        if (acount>0){
            for (int i=0; i<acount; i++){
                UILocalNotification *myUILocalNotification = [narry objectAtIndex:i];
                if (notificationRemoveAction) {
                    if (notificationRemoveAction(myUILocalNotification)) {
                        [[UIApplication sharedApplication] cancelLocalNotification:myUILocalNotification];
                        NSLog(@"移除了本地通知 %@",myUILocalNotification.userInfo);
                    }else{
                        NSLog(@"有本地通知未移除 %@",myUILocalNotification.userInfo);
                    }
                }
            }
        }
    }
}

- (void)removeAllLocalNotification
{
    float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (sysVer >= 10) {
        [[UNUserNotificationCenter currentNotificationCenter]removeAllDeliveredNotifications];
        [[UNUserNotificationCenter currentNotificationCenter]removeAllPendingNotificationRequests];
    }else{
        NSArray *narry=[[UIApplication sharedApplication] scheduledLocalNotifications];
        NSUInteger acount=[narry count];
        if (acount>0){
            for (int i=0; i<acount; i++){
                UILocalNotification *myUILocalNotification = [narry objectAtIndex:i];
                [[UIApplication sharedApplication] cancelLocalNotification:myUILocalNotification];
            }
        }
    }
    
    NSLog(@"清除了本地的所有推送");
}
#pragma mark - 事件处理
#pragma mark - 注册
- (void)registerAPNS
{
    float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
    if (sysVer >= 10) {
        // iOS 10
        [self registerPush10];
    } else if (sysVer >= 8) {
        // iOS 8-9
        [self registerPush8to9];
    } else {
        // before iOS 8
        [self registerPushBefore8];
    }
#else
    if (sysVer < 8) {
        // before iOS 8
        [self registerPushBefore8];
    } else {
        // iOS 8-9
        [self registerPush8to9];
    }
#endif
}

- (void)registerPush10{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    
    
    [center requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            NSLog(@"app推送初始化 -- 》注册成功");
        }else{
            NSLog(@"app推送初始化 -- 》注册失败");
        }
    }];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
#endif
}

- (void)registerPush8to9{
    UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
    UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
}

- (void)registerPushBefore8{
#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_8_0
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
#endif
}




- (void)playNotifySound {
    //获取路径
    NSString *path = [[NSBundle mainBundle] pathForResource:@"candoNotifySound" ofType:@"mp3"];
    //定义一个带振动的SystemSoundID
    SystemSoundID soundID = 1304;
    //判断路径是否存在
    if (path) {
        //创建一个音频文件的播放系统声音服务器
        OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)([NSURL fileURLWithPath:path]), &soundID);
        //判断是否有错误
        if (error != kAudioServicesNoError) {
            NSLog(@"%d",(int)error);
        }
    }
    //只播放声音，没振动
    AudioServicesPlaySystemSound(soundID);
}

#pragma mark - 代理 <UNUserNotificationCenterDelegate>
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{


}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (sysVer >= 10) {
        if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) { //在前台
            if ([notification.request.content.body isEqualToString:@"设备已经断开连接"]) {
                if (DTCEXRACT_OBJECT(@"notDisturb") == nil || [DTCEXRACT_OBJECT(@"notDisturb") isEqualToString:@"NO"]) {
                    [self playNotifySound];
                }
                
                UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"警告" message:@"设备已断开连接" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alterView show];
                
            }
            //        @{@"remind":@"water"}
            if ([notification.request.content.body isEqualToString:@"一杯子提醒您该喝水啦"] || [notification.request.content.body isEqualToString:@"一杯子提醒您该吃药啦"]) {
                if (DTCEXRACT_OBJECT(@"notDisturb") == nil || [DTCEXRACT_OBJECT(@"notDisturb") isEqualToString:@"NO"]) {
                    [self playNotifySound];
                }
                
                UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"提醒" message:notification.request.content.body delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alterView show];
            }
        }
    }

}
@end
